const Subscription = require('egg').Subscription;

class UpdateAsseccToken extends Subscription {

  static get schedule() {
    return {
      interval: '105m',
      type: 'worker',
      immediate: true,
      //disable: true,
    };
  }

  async subscribe() {

    this.ctx.logger.info('刷新accesstoken定时任务开始');

    const wx = await this.ctx.app.redis.get('system').hgetall('dlq_wx');

    this.ctx.logger.info(wx);

    for(let key in wx){

        const wxobj = JSON.parse(wx[key]);

        const appid = wxobj.appid;
        const secret = wxobj.appsecret;
        const wxid = wxobj.wxid;



        const now = new Date();

        this.ctx.logger.info(now + '  开始更新 wxid : ' + wxid + ' 的accesstoken');

        const times = now.getTime();

        if(wxobj.toredis_state == '1'){

            let url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&' + 
            'appid=' + appid + '&secret=' + secret;

            const result = await this.ctx.curl(url, { dataType: 'json' });

            //this.ctx.app.logger.info(result);

            let url1 = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+
              result.data.access_token +'&type=jsapi';

            const result1 = await this.ctx.curl(url1, { dataType: 'json' });

            //this.ctx.app.logger.info(result1);

            let obj = {
                time : times,
                access_token : result.data.access_token,
                jsapi_ticket : result1.data.ticket,
            };

            await this.ctx.app.redis.get('system').hset('dlq_token', wxid, JSON.stringify(obj));

            //临时的 从居游获取accesstoken


            // this.ctx.logger.info('开始更新居游的 accesstoken : ' + wxid);
            // const result = await this.ctx.curl('https://tsv.juyouhx.com/api/uc/wc/accountService/getToken', {
            //     method: 'GET',
            //     contentType: 'json',
            //     data: {
            //         wxid,
            //     },
            //     dataType: 'json',
            // });

            // this.ctx.logger.info(result);

            // if(result.data.errcode == 0){
            //     this.ctx.logger.info('token : ' + result.data.data.token);

            //     let obj = {
            //         time : times,
            //         access_token : result.data.data.token,
            //         jsapi_ticket : result.data.data.ticket,
            //     };

            //     await this.ctx.app.redis.get('system').hset('dlq_token', wxid, JSON.stringify(obj));

            //     this.ctx.logger.info('居游 wxid ： ' + wxid + ' 更新完毕 ');
            // }
            
        }

    }

    this.ctx.app.logger.info('刷新accesstoken定时任务结束');



  }

}

module.exports = UpdateAsseccToken;